//#include <fcntl.h>
//#include <sys/stat.h>
#include <time.h>
#include <iostream>
#include "CKLogFile.h"



namespace K_Engine
{
	CKLogFile::CKLogFile(const std::string strFileName)
	{
		SetFileName(strFileName);
	}
	
	
	CKLogFile::~CKLogFile()
	{
		Close();
	}
	
	
	bool CKLogFile::bOpenFile()
	{
		if(IsOpen())
		{
			return true;
		}
		if(m_strFileName.empty())
		{
			return false;
		}
		m_filefd.open(m_strFileName.c_str(), std::ios::app/*, std::filebuf::sh_none*/);
		return IsOpen();
	}
	
	
	void CKLogFile::Write(const std::string strText)
	{
		if(IsOpen())
		{
			m_filefd<<strText;
		}
	}
	
	
	void CKLogFile::WriteLog(const std::string strText, LOG_TYPE level)
	{
		time_t now;
		char temp[21];
		if(IsOpen())
		{
			now = time(NULL);
			strftime(temp, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
			m_filefd<<"[";
			m_filefd<<temp;
			switch(level)
			{
			case ERROR:
				m_filefd<<" - ERROR   ";
				break;
			case NORMAL:
				m_filefd<<" - NORMAL  ";
				break;
			case WARNING:
				m_filefd<<" - WARNING ";
				break;
			default:
				m_filefd<<" - UNKNOW  ";
			}
			m_filefd<<"]";
			m_filefd<<"    :    "<<strText<<"\n";
			m_filefd.flush();
		}
		else
		{
			std::cout<<"Open Log file error!"<<std::endl;
		}
	}
	
	
	void CKLogFile::Log(const std::string& strText, LOG_TYPE level)
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		if(!bOpenFile())
		{
			std::cout<<"Open Log file error!"<<std::endl;
			return;
		}
		WriteLog(strText, level);
	}
	
	
	void CKLogFile::SetFileName(const std::string& strFileName)
	{
		m_strFileName = strFileName;
		Close();
	}
	
	
	const std::string& CKLogFile::GetFileName()
	{
		return m_strFileName;
	}
	
	
	void CKLogFile::Lock()
	{
		m_mutex.lock();
	}
	
	
	void CKLogFile::UnLock()
	{
		m_mutex.unlock();
	}
	
	
	bool CKLogFile::IsOpen()
	{
		return m_filefd.is_open();
	}
	
	
	void CKLogFile::Close()
	{
		if(IsOpen())
		{
			m_filefd.close();
		}
	}
}